package com.wj.core.net.service;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.wj.core.common.util.EnvironmentUtil;
import com.wj.core.common.util.ZkUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

/**
 * @author: wangjun
 * @create: 2018-06-04
 *
 * 服务注册
 **/
public class ZkServiceRegistry {

  private static final Logger logger = LoggerFactory.getLogger(ZkServiceRegistry.class);

  private static ZooKeeper zooKeeper;

  static {
    if (zooKeeper == null) {
      zooKeeper = ZkUtil.getInstance();
    }
  }

  public static void destory() {
    if (zooKeeper != null) {

      try {
        zooKeeper.close();
      } catch (InterruptedException e) {
        logger.info("zookpeer close error :{}", e);
      }
    }
  }

  public static void registerServices(int port, Set<String> serviceList) throws KeeperException, InterruptedException {
    if (CollectionUtils.isEmpty(serviceList)) {
      return;
    }

    String ip = null;

    try {
      ip = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      logger.info("getHostAddress error :{}", e);
    }

    if (ip == null) {
      return;
    }

    String serverAddress = ip + ":" + port;

    Stat exists = zooKeeper.exists(EnvironmentUtil.ZK_SERVICE_PATH, true);

    if (exists == null) {
      zooKeeper
          .create(EnvironmentUtil.ZK_SERVICE_PATH, new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    for (String interfaceName : serviceList) {
      String interfacePath = EnvironmentUtil.ZK_SERVICE_PATH.concat("/").concat(interfaceName);
      String addressPath =
          EnvironmentUtil.ZK_SERVICE_PATH.concat("/").concat(interfaceName).concat("/").concat(serverAddress);

      Stat existsInter = zooKeeper.exists(interfacePath, true);

      if (existsInter == null) {
        zooKeeper.create(interfacePath, new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      }

      Stat addreddStat = zooKeeper.exists(addressPath, true);
      if (addreddStat != null) {
        zooKeeper.delete(addressPath, -1);
      }
      String path =
          zooKeeper.create(addressPath, serverAddress.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

      logger.info("wj-rpc register success on zookeeper ; interfaceName:{}, serverAddress:{}, addressPath:{} "
          , interfaceName, serverAddress, addressPath);
    }
  }
}
